home *** CD-ROM | disk | FTP | other *** search
- Path: locutus.rchland.ibm.com!usenet
- From: Philip Staite <pstaite@vnet.ibm.com>
- Newsgroups: comp.lang.c++
- Subject: Re: Template casting problem
- Date: Thu, 25 Jan 1996 13:13:56 -0600
- Organization: IBM Rochester, OS/2 Device Driver Team
- Message-ID: <3107D674.41C6@vnet.ibm.com>
- References: <41@site73.site73.ping.at>
- NNTP-Posting-Host: powertool.rchland.ibm.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0b4 (X11; I; AIX 1)
-
- Michael Geramb wrote:
- >
- > Here is a C++ problem that I never managed to solve.
- >
- > Imagine you create a template of a class :
- >
- > template <class T> class A
- > {
- > ...
- > };
- >
- > This gives a family of classes (instances), say:
- >
- > A<short>, A<int>, A<float> etc, which may coexist in one function.
- > Then, a problem arises how to cast one instance to another.
- >
- > As a more concrete example, one may imagine a template CVector which
- > generates short, integer, float and double instances.
- > It also generates a very natural (to my mind) wish to cast
- > one instance to another.
-
- Why, with a templatized function of course! :-)
-
- How about something like this:
-
-
- #include<iostream.h>
-
- // simple vector template
- template<class T>
- class vec {
- public:
- vec( int x ) : n( x ), a( new T[ n ] ) {}
- ~vec() { delete[] a; }
- T& operator[]( int x ) { return a[ x ]; }
- int len() const { return n; }
- private:
- int n;
- T* a;
- };
-
-
- // template function that can convert vecs
- // relies on cast from B& to A being defined
- template<class A, class B>
- void castVec( vec<A>& a, vec<B>& b ) {
- for( int i = 0 ; i < a.len() ; ++i )
- a[ i ] = (A) b[ i ]; }
-
-
-
- int main() {
- vec<float> fvec( 10 );
- vec<int> ivec( 10 );
- int f;
-
- for( f = 0 ; f < 10 ; ++f )
- fvec[ f ] = f;
-
- castVec( ivec, fvec );
-
- for( f = 0 ; f < 10 ; cout << ivec[ f++ ] << endl );
-
- return 0; }
-
-
-
-
-
- --
-
- Phil Staite, (507) 253-2529, team OS/2
- internet: pstaite@vnet.ibm.com internal: pstaite@rchland
-